<template>
  <view class="order-list-page">
    <!-- 订单状态标签 -->
    <view class="tabs-header">
      <view 
        class="tab-item" 
        :class="{ active: currentTab === index }"
        v-for="(tab, index) in tabs" 
        :key="index"
        @click="switchTab(index)"
      >
        <text>{{ tab.name }}</text>
      </view>
    </view>
    
    <!-- 订单列表 -->
    <view class="order-list">
      <!-- 订单项 -->
      <view 
        class="order-item" 
        v-for="(order, index) in filteredOrders" 
        :key="order.id"
        @click="goDetail(order.id)"
      >
        <view class="order-header">
          <view class="order-number">订单号：{{ order.id }}</view>
          <view class="order-status">{{ getStatusText(order.status) }}</view>
        </view>
        
        <view class="product-list">
          <view 
            class="product-item" 
            v-for="(product, pIndex) in order.products" 
            :key="pIndex"
          >
            <image class="product-image" :src="product.image" mode="aspectFill"></image>
            <view class="product-info">
              <view class="product-name">{{ product.name }}</view>
              <view class="product-spec">{{ product.specificationName }}</view>
              <view class="product-price-info">
                <text class="price">{{ product.price.toFixed(2) }}</text>
                <text class="quantity">x{{ product.count }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <view class="order-total">
            <text class="total-label">共</text>
            <text class="total-count">{{ getTotalCount(order.products) }}件商品</text>
            <text class="total-amount">{{ order.totalAmount.toFixed(2) }}</text>
          </view>
          
          <view class="order-actions">
            <view class="action-btn default" v-if="order.status === 1" @click.stop="cancelOrder(order.id)">取消订单</view>
            <view class="action-btn primary" v-if="order.status === 1" @click.stop="payOrder(order.id)">立即支付</view>
            <view class="action-btn default" v-if="order.status === 3" @click.stop="viewLogistics(order.id)">查看物流</view>
            <view class="action-btn primary" v-if="order.status === 3" @click.stop="confirmReceive(order.id)">确认收货</view>
            <view class="action-btn default" v-if="order.status === 4" @click.stop="deleteOrder(order.id)">删除订单</view>
            <view class="action-btn primary" v-if="order.status === 4" @click.stop="buyAgain(order)">再次购买</view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-order" v-if="filteredOrders.length === 0 && !loading">
        <image class="empty-image" src="/static/images/empty-order.png" mode="aspectFit"></image>
        <text class="empty-text">暂无相关订单</text>
        <view class="go-shopping" @click="goShopping">去逛逛</view>
      </view>
      
      <!-- 加载提示 -->
      <view class="loading-more" v-if="loading">
        加载中...
      </view>
      
      <!-- 没有更多数据提示 -->
      <view class="no-more" v-if="filteredOrders.length > 0 && !hasMore">
        没有更多订单了
      </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex';
import orderApi from '@/api/order.js';
import '@/styles/pages/order/list.scss';

export default {
  data() {
    return {
      currentTab: 0,
      tabs: [
        { name: '全部', status: 0 },
        { name: '待付款', status: 1 },
        { name: '待发货', status: 2 },
        { name: '待收货', status: 3 },
        { name: '已完成', status: 4 }
      ],
      orders: [],
      page: 1,
      limit: 10,
      hasMore: true,
      loading: false,
      refreshing: false
    };
  },
  computed: {
    filteredOrders() {
      if (this.currentTab === 0) {
        return this.orders;
      } else {
        return this.orders.filter(order => order.status === this.tabs[this.currentTab].status);
      }
    }
  },
  onLoad(options) {
    // 如果有指定状态，切换到对应标签
    if (options.status) {
      const tabIndex = this.tabs.findIndex(tab => tab.status === Number(options.status));
      if (tabIndex !== -1) {
        this.currentTab = tabIndex;
      }
    }
    
    this.loadOrders();
  },
  methods: {
    ...mapActions('order', [
      'updateOrderList'
    ]),
    
    // 加载订单数据
    async loadOrders() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const params = {
          page: this.page,
          limit: this.limit
        };
        
        // 如果不是"全部"选项，则添加状态过滤
        if (this.currentTab !== 0) {
          params.status = this.tabs[this.currentTab].status;
        }
        
        const res = await orderApi.getOrderList(params);
        
        if (this.page === 1) {
          this.orders = res;
        } else {
          this.orders = [...this.orders, ...res];
        }
        
        // 更新Vuex状态
        this.updateOrderList(this.orders);
        
        // 如果返回的数据少于请求的数量，说明没有更多数据了
        this.hasMore = res.length === this.limit;
        this.page++;
      } catch (error) {
        console.error('加载订单失败', error);
        uni.showToast({
          title: '加载订单失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        if (this.refreshing) {
          this.refreshing = false;
        }
      }
    },
    
    // 刷新数据
    onRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.hasMore = true;
      this.loadOrders();
    },
    
    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return;
      this.loadOrders();
    },
    
    // 切换标签
    switchTab(index) {
      if (this.currentTab === index) return;
      
      this.currentTab = index;
      this.page = 1;
      this.hasMore = true;
      this.orders = [];
      this.loadOrders();
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待付款',
        2: '待发货',
        3: '待收货',
        4: '已完成',
        5: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取订单商品总数
    getTotalCount(products) {
      return products.reduce((count, product) => count + product.count, 0);
    },
    
    // 前往订单详情
    goDetail(id) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${id}`
      });
    },
    
    // 取消订单
    async cancelOrder(id) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '取消中...' });
              await orderApi.cancelOrder(id);
              
              // 刷新订单列表
              this.page = 1;
              this.orders = [];
              await this.loadOrders();
              
              uni.hideLoading();
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '取消订单失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 支付订单
    async payOrder(id) {
      try {
        uni.showLoading({ title: '准备支付...' });
        await orderApi.payOrder(id);
        
        uni.hideLoading();
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
        
        // 刷新订单列表
        this.page = 1;
        this.orders = [];
        this.loadOrders();
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        });
      }
    },
    
    // 查看物流
    viewLogistics(id) {
      uni.navigateTo({
        url: `/pages/order/logistics?id=${id}`
      });
    },
    
    // 确认收货
    async confirmReceive(id) {
      uni.showModal({
        title: '提示',
        content: '确认已收到商品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' });
              await orderApi.confirmOrder(id);
              
              // 刷新订单列表
              this.page = 1;
              this.orders = [];
              await this.loadOrders();
              
              uni.hideLoading();
              uni.showToast({
                title: '确认收货成功',
                icon: 'success'
              });
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '确认收货失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 删除订单
    async deleteOrder(id) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该订单吗？删除后将无法恢复',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' });
              await orderApi.deleteOrder(id);
              
              // 刷新订单列表
              this.page = 1;
              this.orders = [];
              await this.loadOrders();
              
              uni.hideLoading();
              uni.showToast({
                title: '订单已删除',
                icon: 'success'
              });
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '删除订单失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 再次购买
    buyAgain(order) {
      // 将商品添加到购物车
      uni.showLoading({ title: '处理中...' });
      
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '已添加到购物车',
          icon: 'success'
        });
        
        // 跳转到购物车页面
        uni.switchTab({
          url: '/pages/cart/cart'
        });
      }, 500);
    },
    
    // 去逛逛
    goShopping() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
};
</script> 